package com.huanzhidadi.single.stringlock;

/**
 * synchronized 锁字符串常量
 */
public class StringLock {

    public void method() {
        // 因为t1和t2都锁住同一个固定字符串，那么t1持有锁之后，t2永远不会执行
        // String lockString = "字符串常量";
        // 这里将线程t1和线程t2传进来的参数用new方式创建对象。这样就可以保证不是同一个对象。从而打印的会是异步打印
        String lockString = new String("LOCK_STR");
        synchronized (lockString) {
            while (true) {
                try {
                    System.out.println(Thread.currentThread().getName() + "   start");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "   end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        StringLock stringLock = new StringLock();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                stringLock.method();
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            stringLock.method();
        } , "t2");

        t1.start();
        t2.start();
    }
}
